<?php

namespace App\Core;

class VueRuntime
{
    protected Schema $vueComponent;
    protected array $alias = ["v-on"=>"@","v-bind"=>":"];
    protected array $attrs = [];
    protected $options = [];

    public function __construct(Schema $vueComponent){
        $this->vueComponent = $vueComponent;
    }

    /**
     * @param string $instruct
     * @param string $prop
     * @param string $value
     * @return $this
     */
    public function handleAlias(string $instruct,string $prop, string $value): static
    {
        $alia = $this->alias[$instruct];
        $isVOn = str_contains($prop,"$instruct:");
        if ($isVOn){
            $prop = str_replace("$instruct:","",$prop);
        }elseif (!str_contains($prop,$alia)){
            $prop = "{$alia}{$prop}";
        }
        $this->attrs[] = "$prop=\"$value\"";
        return $this;
    }

    /**
     * @param string $prop
     * @param string $value
     * @return $this
     */
    public function vOn(string $prop, string $value): static
    {
        return $this->handleAlias("v-on",$prop,$value);
    }

    /**
     * @param string $prop
     * @param string $value
     * @return $this
     */
    public function vBind(string $prop, string $value): static
    {
        return $this->handleAlias("v-bind",$prop,$value);
    }

    /**
     * @param string $value
     * @return $this
     */
    public function vIf(string $value): static
    {
        $this->attrs[] = "v-if=\"$value\"";
        return $this;
    }

    /**
     * @param string $loopName 循环体变量
     * @param array $items
     * @param string $spec in of
     * @return $this
     */
    public function vFor(string $loopName, array $items = ['item','index'], string $spec = 'in'): static
    {
        $items = implode(",",$items);
        $this->attrs[] = "v-for=\"($items) $spec $loopName\"";
        return $this;
    }

    public function get(){

    }

    public function resolveComponent(string $children){
        $props = $this->vueComponent->getProps();
        $attrs = $this->attrs;
        foreach ($props as $prop=>$value){
            $attrs[] = "$prop=\"$value\"";
        }
        $tagName = $this->vueComponent->getComponentName();
        $attr = implode(" ", $attrs);
        $html = [];
        if ($attr){
            $html[] = "<$tagName $attr>";
        }else{
            $html[] = "<$tagName>";
        }
        if ($children){
            $html[] = "$children";
        }
        $html[] = "</$tagName>";
        return implode(",",$html);
    }
}
